package com.zhiqian.community.interceptor;

import com.zhiqian.community.entity.User;
import com.zhiqian.community.service.MessageService;
import com.zhiqian.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;

    //在处理器处理之前，拦截请求，查询用户是否登陆，并将登陆的用户信息存储到容器中
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null) {
            Object obj = authentication.getPrincipal();
            if (obj != null && obj instanceof User) {
                User user = (User) obj;
                hostHolder.setUser(user);
            }
        }
        return true;
    }

    //Controller处理器处理完，将用户信息添加到模型视图中
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (modelAndView!=null) {
            modelAndView.addObject("loginUser", user);
            if (user!=null){
                modelAndView.addObject("unreadTotal",messageService.selectUserUnreadMessageCount(user.getId()));
            }
        }
    }

    //模板渲染完，清除用户数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.remove();
    }
}
